import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:hbtrans_flutter/beans/tester_list_bean.dart';
import 'package:hbtrans_flutter/utils/mydio.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../apis.dart';
import '../routes.dart';

class TesterPage extends StatefulWidget {
  final organizId;
  final sonOrganizId;
  final status;

  const TesterPage({Key key, this.organizId, this.sonOrganizId, this.status})
      : super(key: key);

  @override
  _TesterPageState createState() => _TesterPageState();
}

class _TesterPageState extends State<TesterPage>
    with AutomaticKeepAliveClientMixin {
  var loadingDialog;
  TesterListBean _testerListBean;
  ScrollController _controller = new ScrollController();

  String loadMoreText = "没有更多数据";
  TextStyle loadMoreTextStyle =
      TextStyle(color: const Color(0xFF999999), fontSize: 14.0);

  _TesterPageState({Key key}) {
    _controller.addListener(() {
      var maxScroll = _controller.position.maxScrollExtent;
      var pixel = _controller.position.pixels;
      if (maxScroll == pixel && items.length < _testerListBean.total) {
        setState(() {
          loadMoreText = "正在加载中...";
          loadMoreTextStyle =
              TextStyle(color: const Color(0xFF4483f6), fontSize: 14.0);
        });
        current++;
        _list(widget.status);
      } else {
        setState(() {
          loadMoreText = "没有更多数据";
          loadMoreTextStyle =
              TextStyle(color: const Color(0xFF999999), fontSize: 14.0);
        });
      }
    });
  }

  var current = 1;
  static int PAGESIZE = 20;
  List<Map<String, dynamic>> maps = List();
  List<RecordsListBean> items = List();

  List<Widget> doWidgets() {
    List<Widget> listTitles = List();
    for (RecordsListBean bean in items) {
      listTitles.add(buildListItem(context, bean));
    }
    return listTitles;
  }

  Widget buildListItem(BuildContext context, RecordsListBean bean) {
    return GestureDetector(
        onTap: () {
          String route = '${Routes.testerDetail}?examnum=${bean.examnum}';
          Routes.router.navigateTo(context, route,
              replace: false, transition: TransitionType.fadeIn);
        },
        child: Row(
          children: <Widget>[
            Image.network(
              bean.photourl,
              height: 48,
              width: 48,
              fit: BoxFit.fill,
            ),
            SizedBox(
              width: 10,
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    Text(
                      bean.name,
                      style: TextStyle(color: Colors.black, fontSize: 14),
                    ),
                    SizedBox(
                      width: 6,
                    ),
                    Text(
                      bean.teachpermitted == null ? '' : bean.teachpermitted,
                      style: TextStyle(color: Color(0xff23afdc), fontSize: 12),
                    )
                  ],
                ),
                SizedBox(
                  height: 6,
                ),
                Text(
                  bean.schName,
                  style: TextStyle(color: Color(0xff666666), fontSize: 12),
                )
              ],
            ),
          ],
        ));
  }

  _setAppbar() {
    if (widget.organizId == null) {
      return null;
    } else {
      return AppBar(
        backgroundColor: Color(0xff23AFDC),
        elevation: 0,
        title: Text('考核员'),
        centerTitle: true,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _setAppbar(),
      body: RefreshIndicator(
        onRefresh: _refresh,
        child: Container(
            color: Colors.white,
            padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
            child: ListView.separated(
              padding: EdgeInsets.all(0),
              controller: _controller,
              shrinkWrap: true,
              itemBuilder: (context, index) => doWidgets()[index],
              separatorBuilder: (context, index) => Divider(
                color: Color(0xffF0F0F0),
              ),
              itemCount: doWidgets().length,
            )),
      ),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _list(widget.status);
  }

  @override
  void dispose() {
    super.dispose();
    MyDio.getInstance().clearInstance();
  }

  Future<Null> _refresh() async {
    items.clear();
    current = 1;
    await _list(widget.status);
    return;
  }

  _list(String status) async {
    Map data = Map<String, dynamic>();
    data["name"] = '';
    data["organizId"] = widget.organizId == null ? '' : widget.organizId;
    data["sonOrganizId"] =
        widget.sonOrganizId == null ? '' : widget.sonOrganizId;
    data["status"] = status;
    data["current"] = current;
    data["pageSize"] = PAGESIZE;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var loginType = await prefs.getString('loginType');
    if (loginType == '2') {
      data['organizId'] = await prefs.getString('loginOrganiz');
    } else if (loginType == '3') {
      data['organizId'] = await prefs.getString('loginOrganiz');
      data['sonOrganizId'] = await prefs.getString('loginSonOrganiz');
    }
    MyDio.getInstance().post(Apis.bussexaList, (data) {
      print(data);
      if (loadingDialog != null) {
        loadingDialog = null;
        Navigator.pop(context);
      }
      _testerListBean = TesterListBean.fromJson(data);
      setState(() {
        items.addAll(_testerListBean.records);
      });
    }, params: data);
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
